package SwingView.Assignment;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import JDBC.InstructorAssignmentActivities;
import SwingController.CmsPresenter;
import SwingModel.CmsAssignment;
import SwingModel.CmsUser;
import SwingView.CmsMainView;

public class ALAssignmentEdit implements ActionListener{

	@Override
	public void actionPerformed(ActionEvent e) {
		CmsUser user = CmsPresenter.user;
		CmsMainView mainView = CmsPresenter.mainView;
		CmsCPAsgmEdit asgmEditPage = mainView.getContentPanel().getAsgmEditPage();
		
		if(asgmEditPage.validateAllInput() == true){
			CmsAssignment edittedAsgm = asgmEditPage.getEdittedAssignment();
			CmsAssignment originalAsgm = asgmEditPage.getOriginalAssignment();
			
			//copy files to local "AsgmFile" folder and modify file path
			List<File> asgmFiles = edittedAsgm.getListOfFile();
			List<File> newFiles = new ArrayList();
			for(File file : asgmFiles){
				try {
					Files.copy(Paths.get(file.getPath()),
							Paths.get("./AsgmFiles/" + file.getName()), 
							StandardCopyOption.REPLACE_EXISTING);
					newFiles.add(new File("./AsgmFiles/" + file.getName()));
				} catch (IOException e1) {
					JOptionPane.showMessageDialog(mainView, "System cannot locate this file on your system:\n\n" + file.getName() + "\n\n Post assignment is aborted" );
					return;
				}
			}
			edittedAsgm.setListOfFile(newFiles);
			System.out.println("ORIGINAL ASSIGNMENT:\n" + originalAsgm.toString());
			System.out.println("Submit EDITTED ASSIGNMENT:\n" + edittedAsgm.toString());
			
			//TODO: GAYATHRI, modify this edit assignment method call as you want
			InstructorAssignmentActivities.editAssignment(CmsPresenter.user.getSelectedCourse().getCourseID(), edittedAsgm);
			
			//TODO: GAYATHRI, modify this get list of assignment method call as you want
			mainView.displayAssignmentInstructorPage(InstructorAssignmentActivities.getListOfAssignments(CmsPresenter.user.getSelectedCourse().getCourseID()));
		}
	}

}